package edu.ccut.saturn.component.utils;

import com.alisoft.xplatform.asf.cache.ICacheManager;
import com.alisoft.xplatform.asf.cache.IMemcachedCache;
import com.alisoft.xplatform.asf.cache.memcached.CacheUtil;
import com.alisoft.xplatform.asf.cache.memcached.MemcachedCacheManager;

import edu.ccut.saturn.component.utils.cache.SaturnMemCache;
import edu.ccut.saturn.core.impl.HostActivator;

public class SaturnMemCacheManager {

	private static SaturnMemCacheManager instance = null;

	private static ICacheManager<IMemcachedCache> memcachedCacheManager;

	private static final String CACHECONFIG = "saturnCache.xml";

	public static final String DEFAULTCLIENT = "client";

	static {
		instance = new SaturnMemCacheManager();
	}

	private SaturnMemCacheManager() {
		// memcachedCacheManager = CacheUtil.getCacheManager(
		// IMemcachedCache.class, MemcachedCacheManager.class.getName());
		memcachedCacheManager = (ICacheManager<IMemcachedCache>) CacheUtil
				.getInstanceByInterface(ICacheManager.class, LoaderUtils
						.getBundleClassLoader(), MemcachedCacheManager.class
						.getName(), true);

		memcachedCacheManager.setConfigFile(CACHECONFIG);
		memcachedCacheManager.start();
	}

	public static SaturnMemCacheManager getInstance() {
		return instance;
	}

	public void reload() {
		memcachedCacheManager.reload(CACHECONFIG);

	}

	public void start() {
		memcachedCacheManager.start();
	}

	public void stop() {
		memcachedCacheManager.stop();
	}

	/**
	 * 如果cacheClient为空，返回默认客户端
	 */
	public ISaturnMemCache getSaturnCache(String cacheClient) {
		String client = null;
		if (cacheClient != null && !"".equals(cacheClient)) {
			client = cacheClient;
		} else {
			client = DEFAULTCLIENT;
		}
		return new SaturnMemCache(memcachedCacheManager.getCache(client));
	}

}
